import mongoose from '../config/DBHelper'
import moment from 'moment'
const Schema = mongoose.Schema
const userSchema = new Schema({
  username: { type: String, index: { unique: true }, sparse: true },
  password: { type: String },
  name: { type: String },
  created: { type: Date },
  updated: { type: Date },
  favs: { type: Number, default: 100 },
  gender: { type: Number, default: 0 },
  roles: { type: Array, default: ['user'] },
  pic: { type: String, default: '/img/header.jpg' },
  mobile: { type: String, match: /^1[3-9](\d{9})$/ },
  status: { type: Number, default: 1 },
  remark: { type: String, default: '' },
  location: { type: String, default: '' },
  isVip: { type: Number, default: 0 },
  count: { type: Number, default: 0 }
})
userSchema.pre('save', function (next) {
  this.created = moment().format('YYYY-MM-DD HH:mm:ss')
  next()
})

userSchema.pre('update', function (next) {
  this.updated = moment().format('YYYY-MM-DD HH:mm:ss')
  next()
})

userSchema.post('save', function (error, doc, next) {
  if (error.name === 'MongoError' && error.code === 11000) {
    next(new Error()('Error:Mongoose has a duplicate key '))
  } else {
    next(error)
  }
})
userSchema.statics = {
  findById (id) {
    return this.findOne({
      _id: id
    }, {
      password: 0,
      // username: 0,
      mobile: 0
    })
  },
  getUserList (page, limit, options = {}) {
    const query = {}
    if (options.key && options.value !== '') {
      if (options.key === 'roles') {
        query[options.key] = { $in: options.value }
      } else if (options.key === 'created') {
        const start = options.value[0]
        const end = options.value[1]
        query[options.key] = { $gte: start, $lt: end }
      } else if (['name', 'username'].includes(options.key)) {
        query[options.key] = { $regex: new RegExp(options.value) }
        // => {name: {regex:/admin/}} => mysql %admin% 模糊查询
      } else {
        query[options.key] = options.value
      }
    }
    return this.find(query, {
      password: 0
    }).skip(page * limit).limit(limit)
  },
  getUserCount () {
    return this.find().countDocuments()
  }
}
const UserModel = mongoose.model('user', userSchema)

export default UserModel
